import upload from '@/utils/upload'
import { toast, showConfirm, tansParams } from '@/utils/common'
import { mergeChunk } from '@/api/print/upload.js'
import { login } from '../api/login';
import { addFile } from '@/api/file/index.js'

//分包大小
const CHUNKSIZE = 1024 * 50;
// const CHUNKSIZE = 10;
//分包缓存
let uploadchunklist = []
//工作线程
let workThread = null;

//文件秒传
async function verifyUpload(filename, fileHash) {
	return { shouldUpload: true}; //默认应该上传
	const { data } = await this.request({
		url: "http://localhost:3000/verify",
		headers: {
			"content-type": "application/json"
		},
		data: JSON.stringify({
			filename,
			fileHash
		})
	});
	return JSON.parse(data);
}


//文件上传控制
async function handleUpload(file) {
	// let file = fileItem.file  
	if (!file) return; 
	// console.log('fileChunkList',fileChunkList);
	const fileChunkList = createFileChunk(file);
	file.hash = await calculateHash(fileChunkList);
	// console.log('file.hash',file.hash);
	const { shouldUpload } = await verifyUpload(
		file.name,
		file.hash
	);
	if(!shouldUpload) {
		this.$message.success("秒传：上传成功");
		return;
	}
	let chunkdata = fileChunkList.map(({chunk,chunkPath}, index) => ({
		chunkPath,
		chunkHash: file.hash + '-' + index,		
		index, 
		chunk, 
		percentage: 0
	}));
	file.chunkdata = chunkdata
	console.log('文件分片chunkdata',chunkdata);
	await uploadChunks(file,chunkdata);
} 

//worker线程
function calculateHash(fileChunkList) {
  return new Promise(resolve => {
    workThread = new Worker('./static/hash.js');
    workThread.postMessage({ fileChunkList });
    workThread.onmessage = e => {
      const { percentage, hash } = e.data;
      // if (this.tempFilesArr[fileIndex]) {
      //   this.tempFilesArr[fileIndex].hashProgress = Number(
      //     percentage.toFixed(0)
      //   );
      // }
      if (hash) {
        resolve(hash);
      }
    };
  });
}

//分包切片
function createFileChunk(file, size = CHUNKSIZE) {
	if(file.size/size > 100) size = file.size/100;
	file.chunklength =  Math.ceil(file.size/size); 
	const fileChunkList = [];
	var count = 0;
	let index = 0;
	console.log('count',count);
	console.log('file.size',file.size);	
	while (count < file.size) {
		let chunk = file.slice(count, count + size)
		fileChunkList.push({
			chunk,
			chunkPath: URL.createObjectURL(chunk),
		});
		// console.log('file.slice',file.slice(count, count + size));
		count += size;
	}
	return fileChunkList;
}

//并发控制
const sendRequest = (file, requestList, max, callback) => {
  let finished = 0;
	let running = 0;
  const total = requestList.length;
  const handler = async() => {
		running ++;
    if (requestList.length) {
      const formData = requestList.shift();
			upload({
						 url: '/file/uploadChunk',
						 file,
						 formData,
						 chunkPath: formData.get('chunkPath'), 
			}).then(() => {
          finished++;
          handler();
        })
        .catch((err) => {
          throw Error(err);
        }).finally(()=>{
					running --;
					if(running == 0 && finished < total){
						uni.showToast({
							icon: 'none',
							title: '分包丢失，请检查网络后重试',
							duration: 2000
						}); 
					}
				})
    }
 
    if (finished >= total) {
      // callback();
			let res = await mergeChunk(file.hash,file.name,CHUNKSIZE);
			if(res.code != 200){
				toast('合并失败,请重试')
				return 
			}
			file.progress += 1;
			let res2 = await addFile(file.name,'pdf',file.hash,file.size,);
			if(res2.code != 200){
				toast('文件信息添加失败,请重试')
				return 
			}
    }
  };
  // for控制初始并发
  for (let i = 0; i < max; i++) {
    handler();
  }
};
 
const urls = Array.from({ length: 10 }, (v, k) => k);
  
const max = 4;
 
const callback = () => {
  console.log('所有请求执行完毕');
};
 
//bloburl转blob对象
function fetch(url){
	return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest();
			xhr.open('GET', url, true);
			xhr.responseType = 'blob';
			xhr.onload = function onload(e) {
				console.log(this.response);
				if (this.status === 200) {
					const Blob = this.response;
					resolve(Blob);
				} else {
					reject(this.status, e);
				}
			};
			xhr.send();
		}); 
}

			// chunk: file.slice(count, count + size),
			// chunkPath: URL.createObjectURL(file),
			// chunkHash: file.hash + '-' + index,
// 上传切片
async function uploadChunks(file,chunklist) { 
	 let requestList = chunklist.map(
		 ({ chunk, chunkPath, chunkHash }) => {
			 const formData = new FormData();
			 formData.append("fileName", file.name);
			 formData.append("fileHash", file.hash); 
			 formData.append("chunkPath", chunkPath);
			 formData.append("chunkHash", chunkHash); 
			 return formData
			 upload({
			 			 url: '/file/uploadChunk',
			 			 file,
			 			 formData,
			 			 chunkPath: formData.get('chunkPath'),
			 			 index: formData.index,
			 })
		 }
		)
	 // requestList2.push()
	 // 并发切片 
	 // console.log('requestList',requestList);
	 sendRequest(file, requestList, 5);
	 // Promise.all(requestList).then(async(resss)=>{
		// console.log(1,resss);
		// let res = await mergeChunk(file.hash,file.name,CHUNKSIZE);
		// if(res.code != 200){
		// 	toast('合并失败,请重试')
		// 	return 
		// }
		// file.progress += 1;
		// console.log(res);		
	 // }).catch((resss)=>{
		//  console.log('222222',resss);
	 // }) 
	 //1、询问后台拼接成功与否
			//1.1成功，uploadedChunkList删除分包缓存，并commit	
			//1.2失败，查什么重新发什么
					//1.1.1成功，uploadedChunkList删除分包缓存
					//1.1.2失败，直接返回	
}
 
export async function uploadFile(fileList){
	// this.uploadchunklist = uploadchunklist
	// console.log('@@@',fileList[0]); 
	// let fileBlob = await fetch(fileList[0]).then(r => r);
	// await handleUpload(fileBlob);
	// return
	//1、获取blob对象
	let fileBlobList = []
	for(let i=0;i<fileList.length;i++){ 
		fileBlobList.push(await fetch(fileList[i]).then(file => {
			fileList[i].file = file
			return fileList[i]
		}));
	}
	// console.log('fileBlobList###:',fileBlobList);
	// return;
	//  fileBlobList = await fileList.map(async(item)=>{
	// 	return await fetch(item).then(r => r);
	// })
	//2、文件上传
	console.log('fileBlobList',fileBlobList);
	await fileBlobList.map(async item=>{
		await handleUpload(item);
	}) 
	// console.log('chunklist',chunklist);
}

 
